<template>
  <el-form ref="form" :model="user" :rules="rules" label-width="80px">
    <el-form-item :label="$t('profile.oldPassword')" prop="password">
      <el-input v-model="user.password" :placeholder="$t('profile.oldPasswordInput')" type="password" />
    </el-form-item>
    <el-form-item :label="$t('profile.newPassword')" prop="newPassword">
      <el-input v-model="user.newPassword" :placeholder="$t('profile.newPasswordInput')" type="password" />
    </el-form-item>
    <el-form-item :label="$t('profile.confirmPassword')" prop="confirmPassword">
      <el-input v-model="user.confirmPassword" :placeholder="$t('profile.confirmPasswordInput')" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="mini" @click="submit">{{ $t('save') }}</el-button>
      <el-button type="danger" size="mini" @click="close">{{ $t('closeText') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updatePwd } from '@/api/system/user'
import { resetRouter } from '@/router/router'

export default {
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.user.newPassword !== value) {
        callback(new Error(this.$t('loginLog.differentPassword')))
      } else {
        callback()
      }
    }
    return {
      test: '1test',
      user: {
        password: undefined,
        newPassword: undefined,
        confirmPassword: undefined
      },
      // 表单校验
      rules: {
        password: [
          { required: true, message: this.$t('loginLog.oldPasswordEmpty'), trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: this.$t('loginLog.newPasswordEmpty'), trigger: 'blur' },
          { min: 6, max: 20, message: this.$t('loginLog.passwordLength'), trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: this.$t('loginLog.enterPasswordEmpty'), trigger: 'blur' },
          { required: true, validator: equalToPassword, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          updatePwd(this.user.password, this.user.newPassword).then(
            response => {
              if (response.code === 0) {
                this.$store.dispatch('LogOut').then(() => {
                  resetRouter()
                  this.$router.push({ path: '/login' })
                })

                this.msgSuccess(this.$t('loginLog.changeSuccess'))
              } else {
                this.msgError(response.msg)
              }
            }
          )
        }
      })
    },
    close() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push({ path: '/wel/index' })
    }
  }
}
</script>
